﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace VntNet.PowerSchemeSwitcher
{
    internal class PowerLineHelper
    {
        internal enum PowerLineStatus : byte
        {
            Battery = 0,
            AC = 1,
            Unknown = 255
        }

        public event Action<PowerLineStatus> OnPowerLineStatusChanged;

        public PowerLineHelper()
        {
            SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
        }

        void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            if(OnPowerLineStatusChanged!=null)
                OnPowerLineStatusChanged((PowerLineStatus)e.Mode);
        }

        public static PowerLineStatus GetCurrentSystemPowerStatus()
        {
            return PowerLineNativeHelper.GetCurrentSystemPowerStatus();
        }

        class PowerLineNativeHelper
        {
            [Flags]
            enum BatteryFlag : byte
            {
                High = 1,
                Low = 2,
                Critical = 4,
                Charging = 8,
                NoSystemBattery = 128,
                Unknown = 255
            }

            [StructLayout(LayoutKind.Sequential)]
            struct SystemPowerStatus
            {
                internal PowerLineStatus PowerLineStatus;
                internal BatteryFlag BatteryFlag;
                internal byte BatteryLifePercent;
                internal byte Reserved1;
                internal uint BatteryLifeTime;//number of second
                internal uint BatteryFullLifeTime;
            }

            [DllImport("kernel32")]
            static extern bool GetSystemPowerStatus(out SystemPowerStatus sps);

            public static PowerLineStatus GetCurrentSystemPowerStatus()
            {
                SystemPowerStatus SysPowerStartus;
                if(GetSystemPowerStatus(out SysPowerStartus))
                    return SysPowerStartus.PowerLineStatus;
                else
                    return PowerLineStatus.Unknown;
            }
        }

    }
}
